package br.edu.ufcg.ga.population;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.Gene;
import org.jgap.IChromosome;
import org.jgap.InvalidConfigurationException;
import org.jgap.RandomGenerator;

public class RandomInitialPopulationGenerator implements InitialPopulationGenerator {

	@SuppressWarnings("serial")
	@Override
	public IChromosome[] createSampleChromosomes(IChromosome sampleChromosome, Configuration configuration)
			throws InvalidConfigurationException {
		IChromosome[] chromosomes = new IChromosome[configuration.getPopulationSize()];
		Gene[] samplegenes = sampleChromosome.getGenes();

		List<Integer> sampleGenesValues = new ArrayList<Integer>(samplegenes.length - 1);
		for (int i = 1; i < samplegenes.length; i++) {
			sampleGenesValues.add((Integer) samplegenes[i].getAllele());
		}
		final RandomGenerator randomGenerator = configuration.getRandomGenerator();

		for (int i = 0; i < chromosomes.length; i++) {
			Gene[] genes = new Gene[samplegenes.length];

			Collections.shuffle(sampleGenesValues, new Random() {
				protected int next(int i) {
					return randomGenerator.nextInt(i);
				}
			});

			for (int k = 0; k < genes.length; k++) {
				genes[k] = samplegenes[k].newGene();
				if (k == 0) {
					genes[k].setAllele(samplegenes[k].getAllele());
				} else {
					genes[k].setAllele(sampleGenesValues.get(k - 1));
				}
			}
			chromosomes[i] = new Chromosome(configuration, genes);
		}
		return chromosomes;
	}

}
